import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { Button, Form, Input, Card, Space, Select, Table, message } from "antd"
import { SearchOutlined } from "@ant-design/icons"
// 获取接口类型
import {
  IHospitalListsLsType,
  IHospitalCityType,
  Status,
} from "@api/hospital/model/hospitalListsType"
// 获取接口函数
import {
  reqHospitalList,
  reqHospitalFromCity,
  reqHospitalCities,
  reqUpdateHosStatus,
} from "@api/hospital/hospitalLists"

export default function HospitalList() {
  //保存获取的医院列表数据
  const [hospitalListsLs, setHospitalListsLs] = useState<IHospitalListsLsType>()
  // 用于保存table分页器的数据
  const [page, setPage] = useState(1) //保存当前页码
  const [pageSize, setPageSize] = useState(5) //保存当前一页的条数
  const [total, setTotal] = useState(10) //保存接口医院列表的总条数
  const [load, setLoad] = useState(false) //保存加载的状态
  // 用于保存省市区的数据
  const [province, setProvince] = useState<IHospitalCityType>([])
  const [city, setCity] = useState<IHospitalCityType>([])
  const [diristrict, setDiristrict] = useState<IHospitalCityType>([])
  const [hostype, setHostype] = useState<IHospitalCityType>([])
  //用于保存省市区是否在加载的状态
  const [ploading, setPLoading] = useState(false)
  const [cloading, setCLoading] = useState(false)
  const [dloading, setDLoading] = useState(false)
  // 定义对象
  //定义 Option 用于给 Select 设置下拉框
  const [form] = Form.useForm() //创建form对象
  const { Option } = Select
  // 定义navigate对象
  const navigate = useNavigate()

  // 利用生命周期钩子调用接口函数获取医院列表数据
  useEffect(() => {
    getReqHospitalSet(page, pageSize)
    getProvince() //获取省数据
    getHostype() //获取医院类型
  }, [])

  // 把接口函数单独封装
  async function getReqHospitalSet(page: number, pageSize: number) {
    // 让表格处于加载状态
    setLoad(true)
    // 调用axios封装的reqHospitalSet函数，访问医院列表接口获取数据
    const values = form.getFieldsValue() //获取form表单的数据
    const result = await reqHospitalList({
      page,
      pageSize,
      ...values,
    })
    // 将page和pageSize存储起来
    setPage(page)
    setPageSize(pageSize)
    // 将接口返回的数据储存在状态中
    setTotal(result.totalElements)
    setHospitalListsLs(result.content)
    // 让表格处于加载完毕状态
    setLoad(false)
  }

  // form表单对应的事件处理函数
  // form表单 保存 按钮的点击事件
  const onFinish = () => {
    getReqHospitalSet(page, pageSize)
  }
  // form表单 清空 按钮的点击事件
  const formClear = () => {
    form.resetFields()
  }
  // 获取省市区的数据，以及医院类型
  const getProvince = async () => {
    setPLoading(true)
    const result = await reqHospitalFromCity()
    setProvince(result)
    setPLoading(false)
  }
  const getCity = async (value: string) => {
    form.setFieldsValue({
      cityCode: undefined,
      districtCode: undefined,
    })
    setCLoading(true)
    const result = await reqHospitalCities(value)
    setCity(result)
    setCLoading(false)
  }
  const getDistrict = async (value: string) => {
    form.setFieldsValue({
      districtCode: undefined,
    })
    setDLoading(true)
    const result = await reqHospitalCities(value)
    setDiristrict(result)
    setDLoading(false)
  }
  const getHostype = async () => {
    const result = await reqHospitalCities("10000")
    setHostype(result)
  }

  // 设置子页面 跳转 按钮事件处理函数
  const goHospitalShow = (id: number) => {
    return () => {
      navigate("/syt/hospital/hospitalList/show/" + id)
    }
  }
  // 设置子页面 排班 按钮事件处理函数
  const goHospitalSchedule = (hoscode: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalList/schedule/${hoscode}`)
    }
  }

  // 设置表格标题头
  const columns = [
    {
      // 设置该列表头名称
      title: "序号",
      render: (_x: any, _y: any, index: number) => {
        return index + 1
      },
      width: 80, // 设置该列表格宽度
      align: "center" as "center", // 设置该列表格居中
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render: (logo: string) => (
        <img src={"data:image/jpeg;base64," + logo} alt="" width={100} />
      ),
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render: (data: any) => data.param.hostypeString,
    },
    {
      title: "详细地址",
      render: (data: any) => data.param.fullAddress,
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (status: Status) => (status ? "已上线" : "未上线"),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      render: (data: any) => (
        <Space>
          <Button type="primary" onClick={goHospitalShow(data.id)}>
            查看
          </Button>
          <Button type="primary" onClick={goHospitalSchedule(data.hoscode)}>
            排班
          </Button>
          <Button
            type="primary"
            onClick={() => {
              reqUpdateHosStatus(data.id, data.status ? 0 : 1)
              message.success((data.status ? "下线" : "上线") + "成功")
              getReqHospitalSet(page, pageSize)
            }}>
            {data.status ? "下线" : "上线"}
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <Card>
      <Form form={form} layout="inline" onFinish={onFinish}>
        <Form.Item name="provinceCode" style={{ marginBottom: 20 }}>
          <Select
            style={{ width: 200 }}
            placeholder="请选择省"
            loading={ploading}
            onChange={getCity}>
            {province.map((item) => (
              <Option value={item.value}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="cityCode" style={{ marginBottom: 20 }}>
          <Select
            style={{ width: 200 }}
            placeholder="请选择市"
            loading={cloading}
            onChange={getDistrict}>
            {city.map((item) => (
              <Option value={item.value}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="districtCode" style={{ marginBottom: 20 }}>
          <Select
            style={{ width: 200 }}
            loading={dloading}
            placeholder="请选择区">
            {diristrict.map((item) => (
              <Option value={item.value}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="hosname" style={{ marginBottom: 20 }}>
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode" style={{ marginBottom: 20 }}>
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype" style={{ marginBottom: 20 }}>
          <Select style={{ width: 200 }} placeholder="医院类型">
            {hostype.map((item) => (
              <Option value={item.value}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="status" style={{ marginBottom: 20 }}>
          <Select style={{ width: 200 }} placeholder="医院状态">
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item style={{ marginBottom: 20 }}>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item style={{ marginBottom: 20 }}>
          <Button onClick={formClear}>清空</Button>
        </Form.Item>
      </Form>

      <Table
        // 设置表格是否处于加载状态
        loading={load}
        // 设置表格格式
        columns={columns}
        // 添加表格要渲染的数据
        // dataSource={hospitalSetsLs}
        dataSource={hospitalListsLs}
        // 给表格主体没行设置key
        rowKey="id"
        // 设置表格的内边框
        bordered={true}
        // 设置分页器
        pagination={{
          // 设置当前页数
          current: page,
          // 设置一页多少条
          pageSize,
          // 数据总数
          total,
          // 设置展示切换器
          showSizeChanger: true,
          // 指定每页可以显示多少条
          pageSizeOptions: [2, 5, 10],
          // 设置是否可以快速跳转
          showQuickJumper: true,
          // 获取分页器动态改变的数据
          onChange: getReqHospitalSet,
          // 设置总页数显示
          showTotal: (total) => {
            return `总数${total}`
          },
        }}
      />
    </Card>
  )
}
